﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace LibrarySync2.Business.Xml
{
    public static class XmlExtensionMethods
    {
        public static XmlDocument LoadDocument(string path)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");
            var file = new FileInfo(path);
            if (!file.Exists)
                return null;

            var result = new XmlDocument();
            using (var readStream = file.OpenRead())
            {
                result.Load(readStream);
            }

            return result;
        }

        public static string GetNodeValue(this XmlDocument document, string path)
        {
            var node = document.SelectSingleNode(path);
            return (node == null) ?
                string.Empty :
                node.InnerText;
        }

        public static void Serialize(this object toSerialize, FileInfo outputFile)
        {
            Type t = toSerialize.GetType();
            if (t.IsSerializable)
            {
                if (outputFile.Exists)
                    outputFile.Delete();

                XmlSerializer serializer = new XmlSerializer(t);
                using (TextWriter tw = new StreamWriter(outputFile.OpenWrite()))
                {
                    serializer.Serialize(tw, toSerialize);
                    tw.Close();
                }
            }
            else
            {
                throw new InvalidOperationException(string.Format("Objects of type {0} are not serializable.", t.Name));
            }
        }

        public static TSerialized LoadSerializedContent<TSerialized>(this FileInfo inputFile)
            where TSerialized : class
        {
            if (!inputFile.Exists)
                throw new ArgumentException(string.Format(
                    "Input file '{0}' does not exist", inputFile.FullName));

            Type t = typeof(TSerialized);
            if (!t.IsSerializable)
                throw new InvalidOperationException(string.Format(
                    "Unable to deserialize type '{0}'", t.FullName));

            TSerialized result = null;
            XmlSerializer serializer = new XmlSerializer(t);
            using (TextReader reader = new StreamReader(inputFile.OpenRead()))
            {
                result = serializer.Deserialize(reader) as TSerialized;
            }
            return result;
        }
    }
}
